//
//  ViewController.m
//  EasyGo
//
//  Created by newhuidong on 16/1/18.
//  Copyright © 2016年 HuiDong. All rights reserved.
//

#import "LoginViewController.h"
#import "HomeViewController.h"
#import "ForgetPwdViewController.h"
#import "WorkingTableViewController.h"
#import "AFNetworking.h"
#import "AppDelegate.h"
#import "MBProgressHUD+NJ.h"
#import "MBProgressHUD.h"

#import "URL.h"
@interface ViewController ()<UITextFieldDelegate>{
    
    
    UIView * bgView;
//    UITextField *phoneTF;
//    UITextField * pswTF;
    
    UILabel * phoneLabel;
    UILabel * pswLabel;
    
    UIImageView * phoneImageView;
    UIImageView * pswImageView;
    BOOL check;
}
@property(nonatomic,strong)UITextField*phoneTF;
@property(nonatomic,strong)UITextField *pswTF;

@property(nonatomic,strong)UIButton * rememberPsw;
@property(nonatomic,strong)UIButton * forgetPsw;
@property(nonatomic,strong)UIButton * loginButton;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    self.title=@"司机登录";
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:0/255.0f green:128/255.0f blue:255/255.0f alpha:1];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];

    self.view.backgroundColor=[UIColor groupTableViewBackgroundColor];

    [self setupUI];
    NSUserDefaults * userDefults=[NSUserDefaults standardUserDefaults];
    _phoneTF.text=[userDefults objectForKey:@"userName"];
    _pswTF.text=[userDefults objectForKey:@"userPsw"];

    self.phoneTF.delegate=self;
    self.pswTF.delegate=self;
}

-(void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBar.translucent=NO;
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init]  forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];

    
}
-(void)setupUI{
    
    CGRect frame=[UIScreen mainScreen].bounds;
    
    bgView=[[UIView alloc]initWithFrame:CGRectMake(0, 84, frame.size.width, 100)];
    bgView.backgroundColor=[UIColor whiteColor];
    bgView.layer.borderColor=[UIColor lightGrayColor].CGColor;
    bgView.layer.borderWidth=0.1;
    [self.view addSubview:bgView];
    
    _phoneTF=[self createTextFielfFrame:CGRectMake(110, 10, frame.size.width-110, 30) font:[UIFont systemFontOfSize:16] placeholder:@"请输入用户名"];
   // _phoneTF.keyboardType=UIKeyboardTypeNumberPad;
    _phoneTF.clearButtonMode=UITextFieldViewModeAlways;
    
    _pswTF=[self createTextFielfFrame:CGRectMake(110, 60, frame.size.width-110, 30) font:[UIFont systemFontOfSize:16] placeholder:@"请输入正确的密码"];
    _pswTF.secureTextEntry=YES;
    _pswTF.clearButtonMode=UITextFieldViewModeAlways;
    

    
    
    UIView * view=[[UIView alloc]initWithFrame:CGRectMake(0, 50, frame.size.width, 1)];
    view.backgroundColor=[UIColor groupTableViewBackgroundColor];
    
    UIView * view1=[[UIView alloc]initWithFrame:CGRectMake(100, 15, 1, 20)];
    view1.backgroundColor=[UIColor grayColor];
    view1.alpha=0.4;
    
    UIView * view2=[[UIView alloc]initWithFrame:CGRectMake(100, 60, 1, 20)];
    view2.backgroundColor=[UIColor grayColor];
    view2.alpha=0.4;
    
    
    
    
    phoneLabel=[[UILabel alloc]initWithFrame:CGRectMake(40, 10, 60, 30)];
    phoneLabel.text=@"用户名";
    phoneLabel.font=[UIFont systemFontOfSize:16];
    
    pswLabel=[[UILabel alloc]initWithFrame:CGRectMake(40, 60, 60, 30)];
    pswLabel.text=@"密    码";
    pswLabel.font=[UIFont systemFontOfSize:16];
    
    self.rememberPsw=[UIButton buttonWithType:UIButtonTypeCustom];
    self.rememberPsw.frame=CGRectMake(10, 200, 20, 20) ;
    
    [self.rememberPsw setBackgroundImage:[UIImage imageNamed:@"no"] forState:UIControlStateNormal];
    
    [self.rememberPsw setBackgroundImage:[UIImage imageNamed:@"yes"] forState:UIControlStateSelected];
    
    UILabel * label=[[UILabel alloc]initWithFrame:CGRectMake(40, 195, 80, 30)];
    label.text=@"记住密码";
    label.font=[UIFont systemFontOfSize:14];
    [self.rememberPsw addTarget:self action:@selector(rememberPswrd:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    self.forgetPsw=[UIButton buttonWithType:UIButtonTypeCustom];
    self.forgetPsw.frame=CGRectMake(frame.size.width-80, self.rememberPsw.frame.origin.y-5, 70, 30);
    [self.forgetPsw setTitle:@"忘记密码?" forState:UIControlStateNormal];
    
    [self.forgetPsw setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    
    [self.forgetPsw setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    
    self.forgetPsw.titleLabel.font=[UIFont systemFontOfSize:15];
    [self.forgetPsw addTarget:self action:@selector(forgetPsword) forControlEvents:UIControlEventTouchUpInside];
    
    self.loginButton=[UIButton buttonWithType:UIButtonTypeCustom];
    self.loginButton.frame=CGRectMake(20, frame.size.width, frame.size.width-40, 40);
    [self.loginButton setBackgroundColor:[UIColor colorWithRed:0/255.0 green:128/255.0 blue:255/255.0 alpha:1]];
    [self.loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.loginButton setTitle:@"登陆" forState:UIControlStateNormal];
    self.loginButton.titleLabel.font=[UIFont systemFontOfSize:17];
    self.loginButton.layer.cornerRadius=3;
    [self.loginButton addTarget:self action:@selector(gotoShoping) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.rememberPsw];
    [self.view addSubview:label];
    [self.view addSubview:self.forgetPsw];
    [self.view addSubview:self.loginButton];
    
    [bgView addSubview:_phoneTF];
    [bgView addSubview:_pswTF];
    [bgView addSubview:view];
    [bgView addSubview:view1];
    [bgView addSubview:view2];
    [bgView addSubview:phoneLabel];
    [bgView addSubview:pswLabel];
    
}
-(void)forgetPsword{
    
    NSLog(@"忘记密码?");
    ForgetPwdViewController * forgetPsw=[[ForgetPwdViewController alloc]init];
    
    [self.navigationController pushViewController:forgetPsw animated:YES];
    
    
}
-(void)viewWillDisappear:(BOOL)animated{
    
    
}
-(void)rememberPswrd:(UIButton *)button{
    
    NSUserDefaults * userDefults=[NSUserDefaults standardUserDefaults];
    
    if (_phoneTF.text.length>0) {
        
        [userDefults setObject:_phoneTF.text forKey:@"userName"];
        
    }
    if (_pswTF.text.length>0) {
        
        [userDefults setObject:_pswTF.text forKey:@"userPsw"];
    }
    [userDefults synchronize];
    
//    if (check) {
//        
//        [self.rememberPsw setBackgroundImage:[UIImage imageNamed:@"yes"] forState:0];
//        NSUserDefaults * user=[NSUserDefaults standardUserDefaults];
//        [user setObject:phoneTF.text forKey:@"Name"];
//        [user setObject:pswTF.text forKey:@"Password"];
//        [user removeObjectForKey:@"Name"];
//        [user removeObjectForKey:@"Password"];
//        
//    }else {
//        
//        [self.rememberPsw setBackgroundImage:[UIImage imageNamed:@"no"] forState:0];
//        NSString * name=@"";
//        NSString * password=@"";
//        NSUserDefaults * user =[NSUserDefaults standardUserDefaults];
//        [user setObject:name forKey:@"Name"];
//        [user setObject:password forKey:@"Password"];
//        [user synchronize];
//    }
//    check=!check;
button.selected=!button.selected;
//    NSLog(@"记住密码");
}
-(void)gotoShoping{
    

    NSLog(@"进入商城");
    [MBProgressHUD showMessage:@""];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self login];
        
    });
    
    
    
}
//登录
-(void)login{
    
    AFHTTPSessionManager * manager=[AFHTTPSessionManager manager];
    manager.responseSerializer=[AFJSONResponseSerializer serializer];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval=10;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    dic[@"userName"]=_phoneTF.text;
    dic[@"password"]=_pswTF.text;
    NSString * urlString=[NSString stringWithFormat:@"%@%@",url1,@"Login"];
    
    [manager POST:urlString parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic=(NSDictionary*)responseObject;
       // NSLog(@"%@",dic);
        
       // NSLog(@"角色:%@",dic[@"Data"]);
       // NSLog(@"状态:%@",dic[@"Status"]);
        
        NSDictionary *data=dic[@"Data"];
                            
        NSString * token=data[@"token"];
    
                            
        
        AppDelegate * tempAppDelegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
        
        tempAppDelegate.token=token;
        
        
        NSLog(@"TOKEN:%@",token);
        
//        if ([dic[@"Status"]isEqualToString:@"0"]) {
//            
//            [self tiaozhuan];
//            NSLog(@"积极急急急");
//        }else{
//            UIAlertController * alert=[UIAlertController alertControllerWithTitle:@"提示" message:@"登录失败" preferredStyle:UIAlertControllerStyleAlert];
//            
//            [alert showViewController:self sender:nil];
//            
//        }
        [self tiaozhuan];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error:%@",error);
    }];
    
}

-(void)tiaozhuan{
    
    UIStoryboard * Story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    WorkingTableViewController * working=[Story instantiateViewControllerWithIdentifier:@"WorkingTableViewController"];
    UINavigationController * nav=[[UINavigationController alloc]initWithRootViewController:working];
    [self presentViewController:nav animated:YES completion:nil];
    
    
    
    
}
-(UITextField *)createTextFielfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextField *textField=[[UITextField alloc]initWithFrame:frame];
    
    textField.font=font;
    
    textField.textColor=[UIColor grayColor];
    
    textField.borderStyle=UITextBorderStyleNone;
    
    textField.placeholder=placeholder;
    
    return textField;
}
-(UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName color:(UIColor *)color
{
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:frame];
    
    if (imageName)
    {
        imageView.image=[UIImage imageNamed:imageName];
    }
    if (color)
    {
        imageView.backgroundColor=color;
    }
    
    return imageView;
}

-(UIButton *)createButtonFrame:(CGRect)frame backImageName:(NSString *)imageName title:(NSString *)title titleColor:(UIColor *)color font:(UIFont *)font target:(id)target action:(SEL)action
{
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=frame;
    if (imageName)
    {
        [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    
    if (font)
    {
        btn.titleLabel.font=font;
    }
    
    if (title)
    {
        [btn setTitle:title forState:UIControlStateNormal];
    }
    if (color)
    {
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
    if (target&&action)
    {
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
    return btn;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma -------------UITextField-----------------

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    
    [self changeButtonAction];
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    [self changeButtonAction];
    return YES;
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    [self changeButtonAction];
    return YES;
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    
    
    [self changeButtonAction];
    return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    [self changeButtonAction];
}
-(void)changeButtonAction{
    
    if ((self.phoneTF.text.length!=0)&&(self.pswTF.text.length!=0)) {
        
        self.loginButton.enabled=YES;
        
    }else{
        
        
        
//        UIAlertController * alert=[UIAlertController alertControllerWithTitle:@"提示" message:@"请输入账号密码" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction * yes=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
//        
//        [alert addAction:yes];
//        
//        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
    
    
    
}




-(void)dealloc{
    
    bgView=nil;
    phoneImageView=nil;
    phoneLabel=nil;
    _phoneTF=nil;
    pswImageView=nil;
    pswLabel=nil;
    _pswTF=nil;
    self.rememberPsw=nil;
    self.forgetPsw=nil;
    self.loginButton=nil;
    NSLog(@"Controller释放了");
    
    
}
@end
